angular.module('com.xbstar.jfhttp', [])
.factory('JFHttp',["$http","$q","UserPackage",function ($http,$q,UserPackage) {
    /**
    * http方法的封装
    */
    var httpmethod=function (params) {
        var deferred=$q.defer();
         $http(params).success(function (data,status,config,headers) {
             var rr=UserPackage.depackage(data); 
             if (rr.status=="200") {
                 deferred.resolve(rr);
             }
             else{
                 deferred.reject({status:rr.status});
             }
         }).error(function(data,status,hedaers,config) {
            console.error("JFHttp-get data from server error,please check the server is working or the param you give for http");
            deferred.reject({status:status});
         });
         return deferred.promise;
    };
    /**
    * post方法的封装
    */
    var post=function (data) {
        var tdata={};
        if(!data) throw new Error("JFHttp-data is null");
        tdata.url=data.url;
        if(!tdata.url) throw new Error("JFHttp-url is null");
        var tmpdata=data.data;
        tdata.headers={'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},
        tdata.params=UserPackage.package(tmpdata);
        tdata.method="post";
        tdata.timeoutTime=50000;
        return httpmethod(tdata);
    };
    /**
    * get方法的封装
    */
     var get=function (data) {
        var tdata={};
        if(!data) throw new Error("JFHttp-data is null");
        tdata.url=data.url;
        if(!tdata.url) throw new Error("JFHttp-url is null");
        var tmpdata=data.data;
        tdata.headers=data.headers|{'Content-Type':'application/x-www-form-urlencoded'},
        tdata.params=UserPackage.package(tmpdata);
        tdata.method="get";
        return httpmethod(tdata);
    };
  return{
      /**
      * data 必须包含 url,
      *可以包含
      *     data字段（参考$ajax的data方法），
      *     headers字段，是一个对象，形如：{'Content-Type':'application/x-www-form-urlencoded'}
      */
    get:function (data) {
        return get(data);
    },
    post:function (data) {
        return post(data);
    }
  }
}])